﻿namespace Blaze.ConfigExporters
{
    using System.Collections.Generic;
    using System.Text;
    using Aspose.Cells;
    using ConfigExportTool;
    using ConfigExportTool.Readers;
    using Configs;

    /// <summary>
    /// 跳转配置导出。
    /// </summary>
    public class NavigationExporter : ExporterBase
    {
        /// <summary>
        /// 导出客户端配置。
        /// </summary>
        protected override void ExportForClient()
        {
            ExportToClient(mDb, "NavigationConfig");
        }

        /// <summary>
        /// 初始化。
        /// </summary>
        protected override void Initialize()
        {
            var workbook = GetWorkbook("跳转配置表.xlsx");
            readNodes(workbook);
            readTasks(workbook);
            mDb = new NavigationDB
            {
                Nodes = mNodes.ToArray(),
                Tasks = mTasks.ToArray(),
            };
        }

        private static string readParameters(WorksheetReader reader, int count)
        {
            var realCount = 0;
            var buffer = new StringBuilder();
            for (var i = 0; i < count; i++)
            {
                var arg = reader.ReadString();
                if (!string.IsNullOrEmpty(arg))
                    realCount++;
                buffer.AppendFormat("{0},", arg);
            }

            if (realCount == 0)
                return null;
            return buffer.ToString().TrimEnd(',');
        }

        private void readNodes(Workbook workbook)
        {
            var worksheet = workbook.Worksheets["跳转配置"];
            var reader = new ByOffsetReader(worksheet.Cells[1, 0]).AsByRow();
            while (!reader.IsEmpty)
            {
                var lineReader = new ByOffsetReader(reader.Current).AsByColumn();
                var node = new NavigationDB.NodeConfig
                {
                    Id = lineReader.ReadInt32(),
                    LogicClass = lineReader.ReadString().Trim(),
                    Parameters = readParameters(lineReader, 4),
                };
                mNodes.Add(node);
                reader.Skip();
            }
        }

        private void readTasks(Workbook workbook)
        {
            var worksheet = workbook.Worksheets["任务配置"];
            var reader = new ByOffsetReader(worksheet.Cells[1, 0]).AsByRow();
            while (!reader.IsEmpty)
            {
                var lineReader = new ByOffsetReader(reader.Current).AsByColumn();
                var node = new NavigationDB.TaskConfig
                {
                    TaskId = lineReader.ReadInt32(),
                    NavigationId = lineReader.ReadInt32(),
                };
                mTasks.Add(node);
                reader.Skip();
            }
        }

        private NavigationDB mDb;
        private readonly List<NavigationDB.NodeConfig> mNodes = new List<NavigationDB.NodeConfig>();
        private readonly List<NavigationDB.TaskConfig> mTasks = new List<NavigationDB.TaskConfig>();
    }
}